package helper.base.file

import java.io.File
import java.io.FileNotFoundException

object FromFileHelper {
    fun <T> String.fileNameToList(
        parseLine: (List<String>) -> T?,
    ): List<T> {
        val file = File(this)
        if (!file.exists()) {
            throw FileNotFoundException("文件 $this 不存在")
        }

        val result = mutableListOf<T>()

        val lines = file.readLines()
        for (line in lines) {
            val values = line.trim().split("\\s+".toRegex())
            parseLine(values)?.let {
                result.add(it)
            } ?: println("Invalid line: $line")
        }

        return result
    }

    fun String.fileNameToDoubleList(): List<Double> {
        return this.fileNameToList {
            if (it.size == 1) {
                it[0].toDoubleOrNull()
            } else {
                null
            }
        }
    }

    fun readDoubleListFromFile(filePath: String): List<Double> {
        return filePath.fileNameToDoubleList()
    }
}